package com.marisfrolg.storage;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnLongClick;
import com.marisfrolg.base.BaseApplication;
import com.marisfrolg.entity.PrepareBinUp;
import com.marisfrolg.entity.PrepareProductUp;
import com.marisfrolg.entity.json.InbItem;
import com.marisfrolg.entity.json.JsonBinStockItemUp;
import com.marisfrolg.entity.json.JsonBinStockUp;
import com.marisfrolg.entity.json.JsonMoveResultUp;
import com.marisfrolg.entity.json.MoveResultMessageUp;
import com.marisfrolg.entity.json.User;
import com.marisfrolg.util.ReadCodeController;
import com.marisfrolg.util.StringUtil;
import com.marisfrolg.util.WebServicesUtil;

public class UpshelfActivity extends ItemActivity {
	private LayoutInflater inflater;
	private PopupWindow popWindow;
	private PopupWindow resultWindow;
	@ViewInject(R.id.triggerBt)
	private com.beardedhen.androidbootstrap.BootstrapButton triggerBt;
	@ViewInject(R.id.showresult)
	private com.beardedhen.androidbootstrap.BootstrapButton showresult;
	@ViewInject(R.id.cangweihao)
	private com.beardedhen.androidbootstrap.BootstrapEditText cangweihao;
	@ViewInject(R.id.cangweihaosingle)
	private com.beardedhen.androidbootstrap.BootstrapEditText cangweihaosingle;
	@ViewInject(R.id.orderno)
	private com.beardedhen.androidbootstrap.BootstrapEditText ordernoedit;
	private BootstrapButton srcconfirm;
	@ViewInject(R.id.kuanhaoList)
	private LinearLayout kuanhaoList;
	@ViewInject(R.id.kuanhaoshu)
	private TextView kuanhaoshu;
	@ViewInject(R.id.zongshu)
	private TextView zongshu;
	@ViewInject(R.id.orderreached)
	private TextView orderreached;
	@ViewInject(R.id.cleanicon)
	private View cleanicon;
	@ViewInject(R.id.inputproduct)
	private com.beardedhen.androidbootstrap.BootstrapEditText inputproduct;
	@ViewInject(R.id.targetbinconfirm)
	private BootstrapButton targetbinconfirm;
	@ViewInject(R.id.unworknum)
	private TextView unworknum;
	@ViewInject(R.id.scrollview)
	private ScrollView scrollview;
	@ViewInject(R.id.automode)
	private Switch autoSwitch;
	private LinearLayout cangweiList;
	private BootstrapButton addcangweihao;
	private BootstrapButton cleancangweihao;
	private AlertDialog alert;
	private static final int CLEANNUM=-4444;
	private static final int SCROLLDOWN=-333;
	private String lastestProNo="";
	
	private ReadCodeController rcc;
	private WSHandler wHandler;
	private WebServicesUtil ws;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upshelf);
		inflater=LayoutInflater.from(this);
		ViewUtils.inject(this);
		sHandler=new ScanHandler(this);
		wHandler=new WSHandler(this);
		ws=new WebServicesUtil(this,wHandler);
		rcc=((BaseApplication)getApplication()).getReadCodeController();
		rcc.setHandler(sHandler);
		rcc.Open();
		initPopWindow();
		srcconfirm=(BootstrapButton)findViewById(R.id.srcconfirm);
		refresh();
		//批量移动功能取消
		triggerBt.setVisibility(View.GONE);
		//是否已经选中目的和源仓位
		JsonBinStockUp jbs;
		try {
			jbs = db.findFirst(JsonBinStockUp.class);
			if(jbs!=null&&(!"".equals(jbs.getWHO()))){
				ordernoedit.setText(jbs.getWHO());
			}
			initResultWindow();
		} catch (DbException e) {
			e.printStackTrace();
		}
		ordernoedit.requestFocus();
		ordernoedit.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_UP){
					chooseOrder(null);
					return true;
				}
				return false;
			}
		});
	}
	
	@OnClick(R.id.automode)
	public void autoMode(View v){
		play_sound(true);
	}
	
	@OnClick(R.id.movetitle)
	public void showdetail(View v){
		try {
			List<JsonBinStockItemUp> jlist=db.findAll(Selector.from(JsonBinStockItemUp.class));
			String msg="";
			if(jlist!=null){
				for (JsonBinStockItemUp jb : jlist) {
					msg+=jb.toString();
				}
			}
			Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	
	//清除已扫描款号信息
	@OnLongClick(R.id.cleanicon)
	public void cleanProduct(View v){
		new AlertDialog.Builder(UpshelfActivity.this).setTitle("提示").setMessage("确定删除已扫款号信息吗?").setPositiveButton("确定",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					List<JsonBinStockItemUp> jlist=db.findAll(JsonBinStockItemUp.class);
					if(jlist==null||jlist.size()==0){
						return;
					}
					for (JsonBinStockItemUp jsonBinStockItem : jlist) {
						jsonBinStockItem.setUQUAN(0);
						jsonBinStockItem.setDESTIN_BIN("");
					}
					db.updateAll(jlist, "uquan","destin_bin");
				} catch (DbException e) {
					e.printStackTrace();
				}
				refresh();
				play_sound(true);
			}
		}).setNegativeButton("取消", null).show();
	}
	//清除所有信息
	@OnClick(R.id.cleanicon)
	public void cleanAll(View v){
		new AlertDialog.Builder(UpshelfActivity.this).setTitle("提示").setMessage("确定该页面的所有信息吗?").setPositiveButton("确定",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					db.deleteAll(PrepareBinUp.class);
					db.deleteAll(PrepareProductUp.class);
					db.deleteAll(JsonBinStockUp.class);
					db.deleteAll(JsonBinStockItemUp.class);
					db.deleteAll(JsonMoveResultUp.class);
					db.deleteAll(MoveResultMessageUp.class);
					Intent in=new Intent(UpshelfActivity.this,UpshelfActivity.class);
					startActivity(in);
					finish();
				} catch (DbException e) {
					e.printStackTrace();
				}
				finish();
			}
		}).setNegativeButton("取消", null).show();
	}
	//点击设入仓位信息
	@OnClick(R.id.targetbinconfirm)
	public void setTargetCangwei(View v){
		String bin=cangweihaosingle.getText()+"";
		Message msg=new Message();
		msg.what=ReadCodeController.CODEREAD;
		msg.obj=bin.trim().toUpperCase(Locale.US);
		sHandler.dispatchMessage(msg);
	}
	
	//点击仓位号提供目标仓位号选择
	@OnClick(R.id.cangweihao)
	public void chooseCangwei(View v){
		triggerBt.performClick();
	}
	
	//将目标仓位号信息清空
	@OnLongClick(R.id.cangweihaotitle)
	public void cleancangwei(View v){
		cangweihao.setText("");
		play_sound(true);
	}
	//将目标仓位号信息清空
	@OnLongClick(R.id.cangweihaotitlesingle)
	public void cangweihaotitlesingle(View v){
		cangweihaosingle.setText("");
		play_sound(true);
	}
	//将源仓位号信息清空
	@OnLongClick(R.id.ordernotitle)
	public void cleansrccangwei(View v){
		ordernoedit.setText("");
		play_sound(true);
	}
	//拉取源仓位信息
	@OnClick(R.id.srcconfirm)
	public void chooseOrder(View v){
		String s=ordernoedit.getText()+"";
		s=s.toUpperCase(Locale.US).trim();
		ordernoedit.setText(s);
		if(StringUtil.isEmpty(s)){
			Toast.makeText(this, "请输入订单号", Toast.LENGTH_SHORT).show();
			play_sound(false);
			return;
		}
		try {
			db.deleteAll(JsonMoveResultUp.class);
			db.deleteAll(MoveResultMessageUp.class);
		} catch (DbException e) {
			e.printStackTrace();
		}
		HashMap<String, Object>params=new HashMap<String, Object>();
		Gson gson=new Gson();
		Type type = new TypeToken<User>() {}.getType();
		params.put("USER", gson.toJson(loginUser, type));
		params.put("WHO", s);
		progressDialog = ProgressDialog.show(UpshelfActivity.this, "查询中", "请稍候...", true, true);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				WebServicesUtil.setConnectionTimeOut();
			}
		});
		ws.call(WebServicesUtil.ACTION_MoveBINSTOCKS, params, WebServicesUtil.URL_ACTION_MoveBINSTOCKS, WebServicesUtil.METHOD_ACTION_MoveBINSTOCKS);
	}
	
	//添加一个产品
	@OnClick(R.id.productconfirm)
	public void addProduct(View v){
		String productno=(inputproduct.getText()+"").toUpperCase(Locale.US).trim();
		orderreached.setText(orderreached.getText()+"");
		Message msg=new Message();
		msg.what=ReadCodeController.CODEREAD;
		msg.obj=productno;
		sHandler.dispatchMessage(msg);
	}
	//添加一个产品
	@OnLongClick(R.id.productconfirm)
	public void editProductNum(View v){
		final String productno=(inputproduct.getText()+"").toUpperCase(Locale.US).trim();
		orderreached.setText(orderreached.getText()+"");
		final EditText et=new EditText(this);
		new AlertDialog.Builder(this).setTitle("修改款号:"+productno+" 的数量").setView(et).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try{
					int value=Integer.valueOf((et.getText()+"").trim());
					if(value==0){
						value=CLEANNUM;
					}
					if(value>0||value==CLEANNUM){
						Message msg=new Message();
						msg.what=ReadCodeController.CODEREAD;
						msg.obj=productno;
						msg.arg1=value;
						sHandler.dispatchMessage(msg);
					}
				}catch (Exception e){
					e.printStackTrace();
					Toast.makeText(UpshelfActivity.this, "请输入数字", Toast.LENGTH_LONG).show();
				}
			}
		}).setNegativeButton("取消", null).show();
	}
	
	@OnClick(R.id.submit)
	public void submitMove(View v){
		final HashMap<String, Object>params=new HashMap<String, Object>();
		Gson gson=new Gson();
		Type type = new TypeToken<User>() {}.getType();
		params.put("USER", gson.toJson(loginUser, type));
		JsonBinStockUp jsonBinStock=null;
		List<JsonBinStockItemUp> workItems=new ArrayList<JsonBinStockItemUp>();
		try {
			jsonBinStock=db.findFirst(JsonBinStockUp.class);
			List<JsonBinStockItemUp> jsonBinStockItems=db.findAll(Selector.from(JsonBinStockItemUp.class));
			if(jsonBinStockItems==null||jsonBinStockItems.size()==0){
				jsonBinStockItems=new ArrayList<JsonBinStockItemUp>();
			}
//			jsonBinStock.setDESTBIN((""+cangweihao.getText()).toUpperCase(Locale.US).trim());
			jsonBinStock.setIV_LGNUM(loginUser.getWorklgnum());
			for (JsonBinStockItemUp jb : jsonBinStockItems) {
				if(jb.UQUAN!=0){
					workItems.add(jb);
				}
			}
			jsonBinStock.setMAT_QUAN(workItems);
		} catch (DbException e1) {
			e1.printStackTrace();
		}finally{
			if(jsonBinStock==null||jsonBinStock.notFinish()){
				play_sound(false);
				Toast.makeText(UpshelfActivity.this, "信息未完成", Toast.LENGTH_LONG).show();
				return;
			}
		}
		final String json=gson.toJson(jsonBinStock, JsonBinStockUp.class);
		if(!jsonBinStock.numFinish() ){
			play_sound(true);
			new AlertDialog.Builder(this).setTitle("提示").setMessage("有款号的数量未完成").setPositiveButton("知道了", new android.content.DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					new AlertDialog.Builder(UpshelfActivity.this).setTitle("提示").setMessage("是否提交当前操作").setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							
							params.put("MOVEIN",json);
							progressDialog = ProgressDialog.show(UpshelfActivity.this, "提交中", "请稍候...", true, true);
							progressDialog.setCanceledOnTouchOutside(false);
							progressDialog.setOnCancelListener(new OnCancelListener() {
								public void onCancel(DialogInterface dialog) {
									WebServicesUtil.setConnectionTimeOut();
								}
							});
							ws.call(WebServicesUtil.ACTION_MoveBINS, params, WebServicesUtil.URL_ACTION_MoveBINS, WebServicesUtil.METHOD_ACTION_MoveBINS);
						}
					}).setNegativeButton("取消", null).show();
				}
			}).setNegativeButton("取消", null).show();
		}else{
			new AlertDialog.Builder(UpshelfActivity.this).setTitle("提示").setMessage("是否提交当前操作").setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					
					params.put("MOVEIN",json);
					progressDialog = ProgressDialog.show(UpshelfActivity.this, "提交中", "请稍候...", true, true);
					progressDialog.setCanceledOnTouchOutside(false);
					progressDialog.setOnCancelListener(new OnCancelListener() {
						public void onCancel(DialogInterface dialog) {
							WebServicesUtil.setConnectionTimeOut();
						}
					});
					ws.call(WebServicesUtil.ACTION_MoveBINS, params, WebServicesUtil.URL_ACTION_MoveBINS, WebServicesUtil.METHOD_ACTION_MoveBINS);
				}
			}).setNegativeButton("取消", null).show();
			
		}
	}
	
	
	//初始化仓位选择弹出窗口
	@SuppressWarnings("deprecation")
	private void initPopWindow() {
		final View vPopupWindow=inflater.inflate(R.layout.move_pop_window, null, false);
		triggerBt.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(popWindow.isShowing()){
					popWindow.dismiss();
				}else{
					popWindow.showAsDropDown(triggerBt, 100, 10);
				}
			}
		});
		popWindow = new PopupWindow(vPopupWindow, 600, 600,true);
		popWindow.setOutsideTouchable(true);
		popWindow.setFocusable(true);
		popWindow.setBackgroundDrawable(new BitmapDrawable());
		cangweiList=(LinearLayout)vPopupWindow.findViewById(R.id.cangweiList);
		cleancangweihao=(BootstrapButton)vPopupWindow.findViewById(R.id.cleancangweihao);
		cleancangweihao.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				new AlertDialog.Builder(UpshelfActivity.this).setTitle("提示").setMessage("确定清空所有已扫仓位?").setPositiveButton("确定",new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						try {
							db.deleteAll(PrepareBinUp.class);
							refreshWindow();
						} catch (DbException e) {
							e.printStackTrace();
						}
					}
				}).setNegativeButton("取消", null).show();
			}
		});
		addcangweihao=(BootstrapButton)vPopupWindow.findViewById(R.id.addcangweihao);
		addcangweihao.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final EditText binno=new EditText(UpshelfActivity.this);
				LayoutParams lp=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
				binno.setLayoutParams(lp);
				alert=new AlertDialog.Builder(UpshelfActivity.this).setView(binno).setTitle("添加仓位号...").setMessage("输入仓位号:(直接扫描可添加)").setPositiveButton("确定",new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Message msg=new Message();
						msg.what=ReadCodeController.CODEREAD;
						msg.obj=(binno.getText()+"").toUpperCase(Locale.US).trim();
						sHandler.dispatchMessage(msg);
						refreshWindow();
					}
				}).setNegativeButton("取消", null).create();
				alert.setOnKeyListener(new DialogInterface.OnKeyListener() {
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						if(event.getAction()==KeyEvent.ACTION_DOWN&&(keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10|| keyCode == KeyEvent.KEYCODE_F11||keyCode == KeyEvent.KEYCODE_BACK)){
							rcc.scan_start();
						}else if(event.getAction()==KeyEvent.ACTION_UP&&(keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10|| keyCode == KeyEvent.KEYCODE_F11)){
							rcc.scan_stop();
						}
						return false;
					}
				});
				alert.setCancelable(false);
				alert.show();
			}
		});
		refreshWindow();
	}
	@OnLongClick(R.id.showresult)
	public void delResult(View v){
		new AlertDialog.Builder(UpshelfActivity.this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					db.deleteAll(JsonMoveResultUp.class);
					db.deleteAll(MoveResultMessageUp.class);
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
		}).setTitle("提示").setMessage("删除结果集?").show();
	}
	
	@SuppressWarnings("deprecation")
	private boolean initResultWindow() throws DbException{
		final View vPopupWindow=inflater.inflate(R.layout.move_popresult_window, null, false);
		resultWindow = new PopupWindow(vPopupWindow,500,700,true);
		resultWindow.setOutsideTouchable(true);
		resultWindow.setFocusable(true);
		resultWindow.setBackgroundDrawable(new BitmapDrawable());
		showresult.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(resultWindow.isShowing()){
					resultWindow.dismiss();
				}else{
					resultWindow.showAsDropDown(showresult);
				}
			}
		});
		TextView title=(TextView) vPopupWindow.findViewById(R.id.title);
		JsonMoveResultUp jmr=db.findFirst(JsonMoveResultUp.class);
		if(jmr!=null&&(!"".equals(jmr.getSUM_UNPRO()))){
			title.setText(jmr.getSUM_UNPRO()+"");
			unworknum.setText(jmr.getSUM_UNPRO()+"");
		}else if(jmr==null||"".equals(jmr.getSUM_UNPRO())||jmr.getSUM_UNPRO()==null){
			//List<JsonBinStockItemUp> list = db.findAll(JsonBinStockItemUp.class);
			Cursor c=db.execQuery("select sum(quan) sm from binstockitemup");
			c.moveToFirst();
			title.setText(c.getString(0));
			unworknum.setText(c.getString(0));
			if(jmr==null){
				return true;
			}
		}
		LinearLayout resultList=(LinearLayout)vPopupWindow.findViewById(R.id.resultList);
		List<MoveResultMessageUp> msgs=db.findAll(Selector.from(MoveResultMessageUp.class).orderBy("id"));
		boolean hasError=jmr.EV_SEVERITY.contains("E");
		if (msgs!=null&&msgs.size()!=0) {
			for (MoveResultMessageUp tohuOutMessage : msgs) {
				View msgview = inflater
						.inflate(R.layout.pickout_pop_item, null);
				TextView msgid = (TextView) msgview.findViewById(R.id.msgid);
				msgid.setText("" + tohuOutMessage.getID());
				TextView msgnum = (TextView) msgview.findViewById(R.id.msgnum);
				msgnum.setText("" + tohuOutMessage.getNUMBER());
				TextView msgtext = (TextView) msgview
						.findViewById(R.id.msgtext);
				msgtext.setText("" + tohuOutMessage.getMESSAGE());
				TextView msgtype = (TextView) msgview
						.findViewById(R.id.msgtype);
				msgtype.setText("" + tohuOutMessage.getTYPE());
				tohuOutMessage.getID();
				if (tohuOutMessage.getTYPE().contains("E")) {//失败
					msgview.setBackgroundResource(R.drawable.item_bg_red);
					hasError = true;
				} else if (tohuOutMessage.getTYPE().contains("S")) {//成功
					msgview.setBackgroundResource(R.drawable.item_bg_green);
				} else {//其他
					continue;
					//				msgview.setBackgroundResource(R.drawable.item_bg_blue);
				}
				resultList.addView(msgview);
				LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) msgview
						.getLayoutParams();
				lp.topMargin = 10;
			}
		}
		if(hasError){
			showresult.setBootstrapType("danger");
			play_sound(false);
			new AlertDialog.Builder(UpshelfActivity.this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					if(resultWindow.isShowing()){
//						resultWindow.dismiss();
					}else{
						resultWindow.showAsDropDown(showresult);
					}
				}
			}).setTitle("提示").setMessage("提交结果中有错误").show();
		}
		return hasError;
	}
	//更新款号数据
	private void refresh(){
		try {
			kuanhaoList.removeAllViews();
			JsonBinStockUp jbs=db.findFirst(JsonBinStockUp.class);
			if(jbs!=null&&jbs.getWHO()!=null&&(!"".equals(jbs.getWHO()))){
				orderreached.setText(Html.fromHtml("<u>"+jbs.getWHO()+"</u>"));
			}
			List<JsonBinStockItemUp> jsonBinStockItems=db.findAll(Selector.from(JsonBinStockItemUp.class).orderBy("updatetime",false));
			if(jsonBinStockItems==null||jsonBinStockItems.size()==0){
				return;
			}
			OnClickListener o=new OnClickListener() {
				public void onClick(View v) {
					final RelativeLayout p=(RelativeLayout)(v.getParent()); 
					TextView productno=(TextView)p.findViewById(R.id.productno);
					TextView seq=(TextView)p.findViewById(R.id.seq);
					new AlertDialog.Builder(UpshelfActivity.this).setTitle("提示").setMessage("#"+seq.getText()+"-确定减少1个款号为:"+productno.getText()).setPositiveButton("确定",new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							TextView idtv=(TextView)p.findViewById(R.id.id);
							int id=Integer.valueOf(idtv.getText().toString().trim());
							try {
								// 
								JsonBinStockItemUp pp=db.findById(JsonBinStockItemUp.class, id);
								if(pp!=null){
									if(pp.UQUAN>0){
										pp.UQUAN-=1;
										if(pp.UQUAN==0){
											pp.setUpdatetime(null);
										}
										db.update(pp, "uquan","updatetime");
										UpshelfActivity.this.play_sound(true);
									}else{
										Toast.makeText(UpshelfActivity.this, "数量已经为零", Toast.LENGTH_LONG).show();
									}
								}
							} catch (DbException e) {
								e.printStackTrace();
							}
							refresh();
						}
					}).setNegativeButton("取消", null).show();
				}
			};
			int i=0;
			int sum=0;
			for (JsonBinStockItemUp jsonBinStockItem : jsonBinStockItems) {
				if(jsonBinStockItem.getQUAN()==0||jsonBinStockItem.getUQUAN()==0){
					continue;
				}
				i++;
				View cangweiItem = inflater.inflate(R.layout.upshelf_item, null);
				TextView bb=(TextView)cangweiItem.findViewById(R.id.seq);
				bb.setText((i<10?"0":"")+i);
				TextView productno=(TextView)cangweiItem.findViewById(R.id.productno);
				productno.setText(jsonBinStockItem.getMATNR());
				TextView id=(TextView)cangweiItem.findViewById(R.id.id);
				id.setText(""+jsonBinStockItem.getId());
				View reduce=cangweiItem.findViewById(R.id.reduce);
				reduce.setOnClickListener(o);
				TextView quantity=(TextView)cangweiItem.findViewById(R.id.quantity);
				sum+=jsonBinStockItem.UQUAN;
				TextView tbin=(TextView)cangweiItem.findViewById(R.id.targetbin);
				tbin.setText(jsonBinStockItem.getDESTIN_BIN());
//				View line=cangweiItem.findViewById(R.id.disableline);
//				if((jsonBinStockItem.getXFELD()+"").contains("X")){
//					line.setVisibility(View.VISIBLE);
//				}
				SpannableStringBuilder style=new SpannableStringBuilder(""+jsonBinStockItem.UQUAN+"/"+jsonBinStockItem.QUAN);
				int end=(jsonBinStockItem.UQUAN+"").length();
				if(jsonBinStockItem.UQUAN==jsonBinStockItem.QUAN){
					style.setSpan(new ForegroundColorSpan(Color.GREEN),0,end,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				}else{
					style.setSpan(new ForegroundColorSpan(Color.RED),0,end,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				}
				
				quantity.setText(style);
				kuanhaoList.addView(cangweiItem);
				LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) cangweiItem.getLayoutParams();
				lp.topMargin = 5;
			}
			kuanhaoshu.setText(""+i);
			zongshu.setText(""+sum);
		} catch (Exception e) {
			e.printStackTrace();
		}
		sHandler.sendEmptyMessage(SCROLLDOWN);
	}
	//更新预置仓位号
	private void refreshWindow(){
		try {
			cangweiList.removeAllViews();
			List<PrepareBinUp> prepareBins=db.findAll(Selector.from(PrepareBinUp.class).orderBy("date", false));
			if(prepareBins==null||prepareBins.size()==0){
				return;
			}
			//选择仓位按键,和删除按键公用监听
			OnClickListener o=new OnClickListener() {
				public void onClick(View v) {
					final RelativeLayout p=(RelativeLayout)(v.getParent()); 
					if(v.getId()==R.id.choose){
						TextView binno=(TextView)p.findViewById(R.id.binno);
						cangweihao.setText(binno.getText());
						if(popWindow!=null){
							popWindow.dismiss();
						}
					}else if(v.getId()==R.id.reduce){
						TextView binno=(TextView)p.findViewById(R.id.binno);
						new AlertDialog.Builder(UpshelfActivity.this).setTitle("提示").setMessage("确定删除仓位:"+binno.getText()).setPositiveButton("确定",new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								TextView idtv=(TextView)p.findViewById(R.id.id);
								int id=Integer.valueOf(idtv.getText().toString().trim());
								try {
									db.deleteById(PrepareBinUp.class, id);
								} catch (DbException e) {
									e.printStackTrace();
								}
								refreshWindow();
							}
						}).setNegativeButton("取消", null).show();
					}
				}
			};
			//根据数据产生UI
			int i=0;
			for (PrepareBinUp prepareBin : prepareBins) {
				i++;
				View cangweiItem = inflater.inflate(R.layout.move_pop_item, null);
				BootstrapButton bb=(BootstrapButton)cangweiItem.findViewById(R.id.choose);
				bb.setText((i<10?"#0":"#")+i);
				TextView binno=(TextView)cangweiItem.findViewById(R.id.binno);
				binno.setText(prepareBin.getBinno());
				TextView id=(TextView)cangweiItem.findViewById(R.id.id);
				id.setText(""+prepareBin.getId());
				View reduce=cangweiItem.findViewById(R.id.reduce);
				reduce.setOnClickListener(o);
				bb.setOnClickListener(o);
				if(prepareBin.isIsused()){
					TextView isused=(TextView)cangweiItem.findViewById(R.id.isused);
					isused.setText("已使用");
				}
				cangweiList.addView(cangweiItem);
			}
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	
	
	private static class ScanHandler extends Handler {
		WeakReference<UpshelfActivity> wactivity;
		ScanHandler(UpshelfActivity activity) {
			wactivity = new WeakReference<UpshelfActivity>(activity);
		}
		public void handleMessage(Message msg) {
			UpshelfActivity activity = wactivity.get();
			switch (msg.what) {
			case ReadCodeController.CODEREAD:{
				if(("".equals(activity.ordernoedit.getText()+""))&&(activity.popWindow == null || !activity.popWindow.isShowing())){//没有pop窗口时 也没有 源仓位
					if(StringUtil.isEmpty(msg.obj+"")){
						activity.play_sound(false);
					}
					activity.ordernoedit.setText(""+msg.obj);
					activity.srcconfirm.performClick();
				}else if (activity.popWindow == null || !activity.popWindow.isShowing()) {//没有pop窗口时---拿货，目的仓位
					if(StringUtil.isBin(msg.obj+"")){//扫入的是仓位号
						activity.cangweihaosingle.setText(msg.obj+"");
						if(activity.autoSwitch.isChecked()){
							activity.lastestProNo=msg.obj+"";
						}
						int count=activity.kuanhaoList.getChildCount();
						if(count>0){//显示列表中有款号,向其中填入bin信息
							View item=activity.kuanhaoList.getChildAt(count-1);
							TextView tbin=(TextView)item.findViewById(R.id.targetbin);
							tbin.setText(msg.obj+"");
							TextView idTv=(TextView)item.findViewById(R.id.id);
							String id=idTv.getText()+"";
							try {
								JsonBinStockItemUp jb=activity.db.findFirst(Selector.from(JsonBinStockItemUp.class).where(WhereBuilder.b("id","=",id)));
								if(jb!=null){
									jb.setDESTIN_BIN(msg.obj+"");
									activity.db.update(jb, "destin_bin");
								}
							} catch (DbException e) {
								e.printStackTrace();
							}
						}else{
							activity.play_sound(false);
							Toast.makeText(activity, "先扫款号", Toast.LENGTH_LONG).show();;
						}
					}else{//扫入的是产品
						int count=activity.kuanhaoList.getChildCount();
						if(count!=0){//显示信息中有款号,则只能在所有款号全部完成其对应bin号才能继续添加(当前款可添加数量)
							View item=activity.kuanhaoList.getChildAt(count-1);
							TextView tbin=(TextView)item.findViewById(R.id.targetbin);
							TextView productno=(TextView)item.findViewById(R.id.productno);
							if(StringUtil.isEmpty(tbin.getText()+"")&&(!productno.getText().toString().equals(msg.obj+""))){
								activity.play_sound(false);
								Toast.makeText(activity, "先把仓位信息完成", Toast.LENGTH_LONG).show();
								return;
							}
						}
						try {
							activity.inputproduct.setText(""+msg.obj);
//							PrepareProduct pp=activity.db.findFirst(Selector.from(PrepareProduct.class).where(WhereBuilder.b("productno", "=", msg.obj+"")));
							List<JsonBinStockItemUp> jlist=activity.db.findAll(Selector.from(JsonBinStockItemUp.class).where(WhereBuilder.b("matnr","=",msg.obj+"")));
							if(jlist==null||jlist.size()==0){
								jlist=new ArrayList<JsonBinStockItemUp>();
							}
							JsonBinStockItemUp jsbi=null;
							for (JsonBinStockItemUp jsonBinStockItem : jlist) {
								if(jsonBinStockItem.UQUAN<=jsonBinStockItem.QUAN){
									jsbi=jsonBinStockItem;
									break;
								}
							}
							if(jsbi==null||(msg.arg1==0&&jsbi.UQUAN==jsbi.QUAN)){//手输即使库存满了也可以变更,添加进入此方法
								activity.play_sound(false);
								if(jlist.size()>0){
									Toast.makeText(activity, "超出库存", Toast.LENGTH_LONG).show();
								}else{
									Toast.makeText(activity, "没有库存", Toast.LENGTH_LONG).show();
								}
								
								return;
							}
							if(jsbi.getUQUAN()<=jsbi.getQUAN()){
								if(msg.arg1!=0){//手输入的
									if(msg.arg1>jsbi.getQUAN()){//大于总数设置多少是总数
										jsbi.setUQUAN(jsbi.getUQUAN());
									}else if(msg.arg1<0){//设为0
										jsbi.setUQUAN(0);
										jsbi.setUpdatetime(null);
									}else{//大于0小于总数设置多少是多少
										jsbi.setUQUAN(msg.arg1);
									}
								}else{//扫扫描的
									if(jsbi.getUQUAN()==0){
										jsbi.setUpdatetime(new Date(System.currentTimeMillis()));
									}
									jsbi.setUQUAN(jsbi.getUQUAN()+1);
								}

								if(activity.autoSwitch.isChecked()&&(!StringUtil.isEmpty(activity.lastestProNo))){
									jsbi.setDESTIN_BIN(activity.lastestProNo);
								}
								activity.db.update(jsbi, "uquan","updatetime","destin_bin");
							}
							activity.refresh();
						} catch (DbException e) {
							e.printStackTrace();
						}
					}
				} else {
					if(StringUtil.isEmpty(msg.obj+"")){
						new AlertDialog.Builder(activity).setTitle("提示").setMessage("不可为空").setPositiveButton("确定",null).show();
						activity.play_sound(false);
						return;
					}
					try {
						PrepareBinUp pb=activity.db.findFirst(Selector.from(PrepareBinUp.class).where(WhereBuilder.b("binno", "=", msg.obj+"")));
						if(pb!=null){
							new AlertDialog.Builder(activity).setPositiveButton("确定",null).setTitle("提示").setMessage("已存在").show();
							activity.play_sound(false);
							return;
						}
						PrepareBinUp pbb=new PrepareBinUp();
						pbb.setBinno((msg.obj+"").trim().toUpperCase(new Locale("US")));
						pbb.date=new Date(System.currentTimeMillis());
						pbb.setIsused(false);
						activity.db.saveBindingId(pbb);
						activity.refreshWindow();
					} catch (DbException e) {
						e.printStackTrace();
					}
				}
				activity.play_sound(true);
				break;
			}
			case SCROLLDOWN:
				activity.scrollview.fullScroll(ScrollView.FOCUS_DOWN);
				break;
			default:
				break;
			}
		}
	};
	
	
	@Override
	public void onBackPressed() {
		if(popWindow.isShowing()){
			popWindow.dismiss();
			return;
		}
		super.onBackPressed();
	}
	public void play_sound(boolean success) {
		try {
			if(success){
				mediaPlayer = MediaPlayer.create(this, R.raw.success);
			}else{
				mediaPlayer = MediaPlayer.create(this, R.raw.error);
			}
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static class WSHandler extends Handler {
		WeakReference<UpshelfActivity> wactivity;
		WSHandler(UpshelfActivity activity) {
			wactivity = new WeakReference<UpshelfActivity>(activity);
		}

		public void handleMessage(Message msg) {
			UpshelfActivity activity = wactivity.get();
			switch (msg.what) {
			case WebServicesUtil.ACTION_MoveBINSTOCKS:{
				if((msg.obj+"").startsWith("错误")){
					activity.play_sound(false);
					Toast.makeText(activity, msg.obj+"", Toast.LENGTH_LONG).show();
					break;
				}
				activity.jsonToDb(msg.obj+"");
				try {
					activity.initResultWindow();
				} catch (DbException e) {
					e.printStackTrace();
				}
				activity.refresh();
				activity.play_sound(true);
				break;
			}
			case WebServicesUtil.ACTION_MoveBINS:{
				if((msg.obj+"").startsWith("错误")){
					activity.play_sound(false);
					Toast.makeText(activity, msg.obj+"", Toast.LENGTH_LONG).show();
					break;
				}
				Gson gson=new Gson();
				Type type = new TypeToken<JsonMoveResultUp>() {}.getType();
				JsonMoveResultUp jmr=gson.fromJson(msg.obj+"", type);
				try {
					activity.db.deleteAll(JsonMoveResultUp.class);
					activity.db.deleteAll(MoveResultMessageUp.class);
					activity.db.saveBindingId(jmr);
					activity.db.saveAll(jmr.getET_BAPIRET());
					activity.play_sound(true);
					boolean hasError=activity.initResultWindow();
					if(!hasError){
						List<JsonBinStockItemUp> list=activity.db.findAll(JsonBinStockItemUp.class);
						if(list==null||list.size()==0){
							list=new ArrayList<JsonBinStockItemUp>();
						}
						for (JsonBinStockItemUp jsonBinStockItemUp : list) {
							jsonBinStockItemUp.setUQUAN(0);
							activity.db.update(jsonBinStockItemUp,"uquan");
						}
					}
					activity.ordernoedit.setText(activity.orderreached.getText()+"");
					activity.refresh();
					activity.showresult.performClick();
				} catch (DbException e) {
					e.printStackTrace();
				}
				
				break;
			}
			case WebServicesUtil.TIMEOUT:{
				new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("提示").setMessage("连接超时").show();
				break;
			}
			case WebServicesUtil.NETUNREACHABLE:{
				Toast.makeText(activity, "网络无法连接或连接已取消,请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
			if(activity.progressDialog!=null&&activity.progressDialog.isShowing()){
				activity.progressDialog.dismiss();
			}
		}
	}


	public void jsonToDb(String msg) {
		try {
			db.deleteAll(JsonBinStockItemUp.class);//提交成功但是报错,界面不清,所以重新拉取为空也不会删掉之前操作数据
			Gson gson = new Gson();
			Type type = new TypeToken<JsonBinStockUp>() {}.getType();
			JsonBinStockUp jsb=gson.fromJson(msg, type);
			jsb.setWHO(ordernoedit.getText()+"");
			if(jsb.getMAT_QUAN()!=null&&jsb.getMAT_QUAN().size()>0){
				db.deleteAll(JsonBinStockUp.class);
				db.deleteAll(JsonBinStockItemUp.class);
			}
			db.saveBindingId(jsb);
			db.saveAll(jsb.getMAT_QUAN());
		} catch (DbException e) {
			e.printStackTrace();
		}
	};
}
